/*
 * Copyright 2009 SHOP.COM
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.shop.opensocial.mediated.shindig.util;

import com.shop.opensocial.mediated.config.MediatedDriverFactory;
import com.shop.opensocial.mediated.services.OAuthStoreMediator;
import com.shop.opensocial.mediated.shindig.factories.OAuthConsumerMediatorFactory;
import com.shop.opensocial.mediated.shindig.request.MediatedServletFilter;
import com.shop.opensocial.mediated.types.SecurityTokenMediator;
import com.shop.opensocial.mediated.types.OAuthConsumerMediator;
import com.shop.opensocial.mediated.util.OAuthValidator;
import net.oauth.OAuth;
import net.oauth.OAuthAccessor;
import net.oauth.OAuthMessage;
import net.oauth.SimpleOAuthValidator;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Jordan Zimmerman
 */
@SuppressWarnings({"deprecation"})
public class OAuthValidatorImplementation implements OAuthValidator
{
	public static final OAuthValidatorImplementation instance = new OAuthValidatorImplementation();

	@Override
	public String getConsumerKey(HttpServletRequest request) throws Exception
	{
		OAuthMessage 		message = buildMessage(request);
		return message.getConsumerKey();
	}

	@Override
	public OAuthConsumerMediator getConsumer(HttpServletRequest request) throws Exception
	{
		SecurityTokenMediator 			token = MediatedDriverFactory.getDriver().getAuthenticationHandlerMediator().getSecurityTokenFromRequest(request);
		OAuthStoreMediator.ConsumerInfo consumer = MediatedDriverFactory.getDriver().getOAuthStoreMediator().getConsumerKeyAndSecret(MediatedServletFilter.getRequest(), token, null, null);
		return (consumer != null) ? consumer.getConsumer() : null;
	}

	@Override
	public OAuthValidatorResult isValidOAuthQuery(HttpServletRequest request, OAuthConsumerMediator consumer) throws Exception
	{
		if ( consumer == null )
		{
			consumer = getConsumer(request);
		}

		// code based on example found here: http://wiki.opensocial.org/index.php?title=Validating_Signed_Requests

		OAuthMessage 					message = buildMessage(request);
		if ( !consumer.getConsumerKey().equals(message.getConsumerKey()) )
		{
			return errorResult("Incorrect Consumer Key");
		}

		OAuthAccessor 			accessor = new OAuthAccessor(OAuthConsumerMediatorFactory.i.make(consumer));
		try
		{
			message.validateMessage(accessor, new SimpleOAuthValidator());
		}
		catch ( Exception e )
		{
			return errorResult(e.getMessage());
		}

		return new OAuthValidatorResult(null, message.getParameter("opensocial_owner_id"), message.getParameter("opensocial_viewer_id"));
	}

	private OAuthMessage buildMessage(HttpServletRequest request)
	{
		String 					method = request.getMethod();
		String 					requestUrl = request.getRequestURL().toString();
		int						queryIndex = requestUrl.indexOf('?');
		if ( queryIndex > 0 )
		{
			requestUrl = requestUrl.substring(0, queryIndex);
		}
		List<OAuth.Parameter> requestParameters = getRequestParameters(request);
		return new OAuthMessage(method, requestUrl, requestParameters);
	}

	private OAuthValidatorResult errorResult(String error)
	{
		return new OAuthValidatorResult(error, null, null);
	}

	private static List<OAuth.Parameter> getRequestParameters(HttpServletRequest request)
	{
		List<OAuth.Parameter> 	parameters = new ArrayList<OAuth.Parameter>();
		for ( Object e : request.getParameterMap().entrySet() )
		{
			Map.Entry<String, String[]> 	entry = (Map.Entry<String, String[]>)e;
			for ( String value : entry.getValue() )
			{
				parameters.add(new OAuth.Parameter(entry.getKey(), value));
			}
		}

		return parameters;
	}

	private OAuthValidatorImplementation()
	{
	}
}
